<template>
  <view class="play-page">
    <!-- 大图 -->
    <view class="cover-container">
      <view class="cover-box">
        <image class="cover-image" :src="coverImages[0]" mode="aspectFill"></image>
      </view>
    </view>

    <!-- 歌词显示（包含可视化组件） -->
    <view class="lyric-container">
      <bing-lyric 
        :curTime="currentTime"
        :lyrics="lyrics"
        :lyricStyle="{color: '#000', fontSize: '18px',activeColor:'#3cc88c'}"
        :areaStyle="{height:'100%',background:'#fff'}"
        :centerStyle="{color:'#fff'}"
      />
      
      <AudioVisualizer 
        class="audio-visualizer"
        :audioData="audioData" 
        :isPlaying="isPlaying" 
        :barCount="25" 
      />
    </view>

    <!-- 调试信息 -->
    <view class="debug-info" v-if="showDebug">
      <text>音频状态: {{ isPlaying ? '播放中' : '已暂停' }}</text>
      <text>当前时间: {{ formatTime(currentTime) }}</text>
      <text>总时长: {{ formatTime(totalTime) }}</text>
      <text>进度: {{ progressPercent.value.toFixed(1) }}%</text>
      <text>音频数据长度: {{ audioData.length }}</text>
      <text>音频数据最大值: {{ maxAudioData }}</text>
    </view>

    <!-- 设置栏和进度条容器 -->
    <view class="progress-set-container">
      <!-- 倍数设置和音量设置栏 -->
      <transition name="fade-cover">
        <view class="volce-box" v-show="ifMultipleSet || ifvolceSet">
          <view class="text-hint">{{ifMultipleSet ? "倍数设置" : "音量设置"}}</view>
          <view v-if="ifvolceSet" class="slider">
            <view class="volce-zero text">0</view>
            <slider class="slider-com" :value="volceCurrent" activeColor="#3cc88c" backgroundColor="#fff" @change="volceSliderChange" @changing="volceSliderChange" step="1" block-size=18 />
            <view class="volce-full text">{{volceCurrent}}</view>
          </view>
          <view v-if="ifMultipleSet" class="slider uv">
            <uv-subsection inactiveColor="#fff" activeColor="#000" bgColor="#3cc88c" :list="multipleList" :current="multipleCurrent" @change="multipleChange"></uv-subsection>
          </view>
        </view>
      </transition>
      
      <!-- 进度控制 -->
      <transition name="fade-cover">
        <view class="progress-container" v-show="!(ifMultipleSet || ifvolceSet)">
          <view class="time-display">
            <text>{{ formatTime(currentTime) }}</text>
          </view>
          <view class="time-slider">
            <slider class="progress-slider" block-size=10 :value="progressPercent" @changing="onProgressChange" @change="onProgressChange" activeColor="#3cc88c" backgroundColor="#e0e0e0"></slider>
          </view>
          <view class="time-display">
            <text>{{ formatTime(totalTime) }}</text>
          </view>
        </view>
      </transition>
    </view>

    <view class="play-btn-box">
      <view class="set-btn" @click="multipleBtn">
        <image class="img" src="/static/icons/倍数.svg"></image>
      </view>
      <view class="up-btn" @click="prevBtn">
        <image class="img" src="/static/icons/上一首.svg"></image>
      </view>
      <view v-if="!isPlaying" class="play-btn" @click="playBtn">
        <image class="img" src="/static/icons/播放.svg"></image>
      </view>
      <view v-else class="play-btn" @click="pauseBtn">
        <image class="img" src="/static/icons/暂停.svg"></image>
      </view>
      <view class="down-btn" @click="nextBtn">
        <image class="img" src="/static/icons/下一首.svg"></image>
      </view>
      <view class="volce-btn">
        <image v-if="!ifvolceSet" class="img" src="/static/icons/音量.svg" @click="volceBtn"></image>
        <image v-else class="img" src="/static/icons/关闭.svg" @click="closeSetBox"></image>
      </view>
    </view>

    <!-- 侧边社交功能区域 -->
    <view class="social-icons">
      <view class="social-icon" @click="handleCollect">
        <uni-icons type="star" size="28" color="#3cc88c"></uni-icons>
      </view>
      <view class="social-icon" @click="handleComment">
        <uni-icons type="chatbubble" size="28" color="#3cc88c"></uni-icons>
      </view>
      <view class="social-icon" @click="handleShare">
        <uni-icons type="redo" size="28" color="#3cc88c"></uni-icons>
      </view>
    </view>

    <!-- 评论区组件 -->
    <CommentComponent
      :showComment="showComment"
      :commentData="commentData"
      :currentCommentMusicId="currentCommentMusicId"
      @hideCommentEvent="hideComment"
    />
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, computed } from "vue"
import AudioVisualizer from '/components/AudioVisualizer.vue'
// 导入评论区组件
import CommentComponent from '/components/CommentComponent.vue'

// 音频控制
const audioContext = ref(null)
const isPlaying = ref(false)
const currentTime = ref(0)
const totalTime = ref(0)
const progressPercent = ref(0)

// 设置状态
const ifMultipleSet = ref(false)
const ifvolceSet = ref(false)
const volceCurrent = ref(100)

const multiplePlaybackRate = ref(1.0)
const multipleCurrent = ref(1)
const multipleList = ref(['0.5X', '1X', '1.5X'])

// 数据状态
const coverImages = ref([
  "https://picsum.photos/600/600?random=1",
  "https://picsum.photos/600/600?random=2",
])
const lyrics = ref([])

// 音频分析数据
const audioData = ref(new Uint8Array(64).fill(0))
const showDebug = ref(false)
const maxAudioData = computed(() => Math.max(...audioData.value))

// 评论区相关数据
const showComment = ref(false)
const commentData = ref({ list: [] })
const currentCommentMusicId = ref(1) // 假设当前音乐 ID 为 1

// 生命周期钩子
onMounted(() => {
  initAudio()
  loadLyrics('/static/不潮不用花钱 - 林俊杰.lrc')
  initAudioAnalyser()
})

onUnmounted(() => {
  destroyAudio()
})

// 初始化音频
const initAudio = () => {
  audioContext.value = uni.createInnerAudioContext()
  // audioContext.value.src = "/static/林俊杰  - 不潮不用花钱.mp3"
  audioContext.value.src = "/static/林俊杰  - 我们的爱 (Live).mp3"
  audioContext.value.loop = true
  audioContext.value.obeyMuteSwitch = false
  
  // 监听音频事件
  audioContext.value.onCanplay(() => {
    setTimeout(() => {
      totalTime.value = audioContext.value.duration || 0
    }, 500)
  })
  
  audioContext.value.onTimeUpdate(() => {
    currentTime.value = audioContext.value.currentTime || 0
    progressPercent.value = (currentTime.value / (totalTime.value || 1)) * 100
  })
  
  audioContext.value.onPlay(() => {
    isPlaying.value = true
    if (audioAnalyser && !animationFrameId) {
      startAudioAnalysis()
    }
  })
  
  audioContext.value.onPause(() => {
    isPlaying.value = false
    stopAudioAnalysis()
  })
  
  audioContext.value.onError((err) => {
    console.error('音频错误:', err)
    isPlaying.value = false
    uni.showToast({
      title: '播放失败: ' + err.errMsg,
      icon: 'none'
    })
  })
}

// 销毁音频资源
const destroyAudio = () => {
  stopAudioAnalysis()
  
  if (audioContext.value) {
    audioContext.value.destroy()
    audioContext.value = null
  }
  
  if (audioAnalyserContext) {
    audioAnalyserContext.close()
    audioAnalyserContext = null
  }
}

// 音频控制方法
const playBtn = () => {
  if (!audioContext.value) return
  audioContext.value.play()
}

const pauseBtn = () => {
  if (!audioContext.value) return
  audioContext.value.pause()
}

const prevBtn = () => {
  // 上一首逻辑
  console.log('上一首')
}

const nextBtn = () => {
  // 下一首逻辑
  console.log('下一首')
}

// 设置控制方法
const multipleBtn = () => {
  ifMultipleSet.value = true
  ifvolceSet.value = false
}

const volceBtn = () => {
  ifvolceSet.value = true
  ifMultipleSet.value = false
}

const closeSetBox = () => {
  ifMultipleSet.value = false
  ifvolceSet.value = false
}

const multipleChange = (index) => {
  multipleCurrent.value = index
  const rates = [0.5, 1.0, 1.5]
  multiplePlaybackRate.value = rates[index]
  
  if (audioContext.value) {
    audioContext.value.playbackRate = multiplePlaybackRate.value
  }
}

const volceSliderChange = (e) => {
  volceCurrent.value = e.detail.value
  
  if (audioContext.value) {
    audioContext.value.volume = volceCurrent.value / 100
  }
}

const onProgressChange = (e) => {
  const percent = e.detail.value
  progressPercent.value = percent
  const seekTime = (percent / 100) * totalTime.value
  
  if (audioContext.value) {
    audioContext.value.seek(seekTime)
  }
}

// 加载歌词
const loadLyrics = async (lrcPath) => {
  try {
    const res = await uni.request({
      url: lrcPath,
      method: 'GET',
      dataType: 'text'
    })
    
    if (res.statusCode === 200) {
      const lines = res.data.split('\n').filter(line => line.trim())
      lyrics.value = lines
    }
  } catch (error) {
    console.error('加载歌词失败:', error)
  }
}

// 音频分析器
let audioAnalyser = null
let audioAnalyserContext = null
let animationFrameId = null

const initAudioAnalyser = () => {
  try {
    audioAnalyserContext = new (window.AudioContext || window.webkitAudioContext)()
    audioAnalyser = audioAnalyserContext.createAnalyser()
    audioAnalyser.fftSize = 128
    audioAnalyser.smoothingTimeConstant = 0.3
    
    const mediaElement = document.createElement('audio')
    mediaElement.src = audioContext.value.src
    mediaElement.crossOrigin = 'anonymous'
    
    const source = audioAnalyserContext.createMediaElementSource(mediaElement)
    source.connect(audioAnalyser)
    audioAnalyser.connect(audioAnalyserContext.destination)
    
    // 同步音频状态
    audioContext.value.onPlay(() => {
      if (audioAnalyserContext.state === 'suspended') {
        audioAnalyserContext.resume().then(() => {
          mediaElement.currentTime = audioContext.value.currentTime
          mediaElement.play()
        })
      } else {
        mediaElement.currentTime = audioContext.value.currentTime
        mediaElement.play()
      }
    })
    
    audioContext.value.onPause(() => {
      mediaElement.pause()
    })
    
    audioContext.value.onSeeked(() => {
      mediaElement.currentTime = audioContext.value.currentTime
    })
  } catch (error) {
    console.error('初始化音频分析器失败:', error)
    useMockAudioData()
  }
}

const startAudioAnalysis = () => {
  const updateAudioData = () => {
    if (!audioAnalyser || !isPlaying.value) return
    
    const frequencyData = new Uint8Array(audioAnalyser.frequencyBinCount)
    audioAnalyser.getByteFrequencyData(frequencyData)
    audioData.value = frequencyData
    
    animationFrameId = requestAnimationFrame(updateAudioData)
  }
  
  updateAudioData()
}

const stopAudioAnalysis = () => {
  if (animationFrameId) {
    cancelAnimationFrame(animationFrameId)
    animationFrameId = null
  }
}

const useMockAudioData = () => {
  console.log('使用模拟音频数据')
  
  const updateMockData = () => {
    if (!isPlaying.value) return
    
    const t = Date.now() / 1000
    const newData = new Uint8Array(64)
    
    for (let i = 0; i < 64; i++) {
      const freq = i / 64
      const value = Math.sin(t * 2 + freq * 10) * 30 + 
                    Math.sin(t * 3 + freq * 20) * 20 + 
                    Math.sin(t * 5 + freq * 30) * 10 + 50
      
      newData[i] = Math.max(10, Math.min(255, value))
    }
    
    audioData.value = newData
    animationFrameId = requestAnimationFrame(updateMockData)
  }
  
  updateMockData()
}

// 工具函数
const formatTime = (seconds) => {
  if (!seconds || isNaN(seconds)) return "00:00"
  const minutes = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  return `${minutes.toString().padStart(2, "0")}:${secs.toString().padStart(2, "0")}`
}

// 社交功能事件处理函数
const handleCollect = () => {
  console.log('收藏')
}

const handleComment = () => {
  openComment()
}

const handleShare = () => {
  console.log('分享')
}

// 打开评论区
const openComment = () => {
  showComment.value = true
}

// 关闭评论区
const hideComment = () => {
  showComment.value = false
}
</script>

<style lang="scss">
.play-page {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

/* 封面轮播 */
.cover-container {
  width: 100%;
  margin-top: 20rpx;
  height: 450rpx;
  margin-bottom: 40rpx;
  border-radius: 10rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .cover-box {
    height: 100%;
    width: 90%;
  }
  
  .cover-image {
    width: 100%;
    height: 100%;
    object-fit: cover;
    border-radius: 25rpx;
    animation: imgPulse 2s infinite;
  }
  
  @keyframes imgPulse {
    0% {
      box-shadow: 0 0 0 0 rgba(60, 200, 140, 0.5);
    }
    50% {
      box-shadow: 0 0 25rpx 20rpx rgba(60, 200, 140, 0.2);
    }
    100% {
      box-shadow: 0 0 0 0 rgba(60, 200, 140, 0);
    }
  }
}

/* 歌词显示容器 */
.lyric-container {
  height: 680rpx;
  display: flex;
  align-items: center;
  flex-direction: column;
  overflow: hidden;
  position: relative;
}

/* 音频可视化组件 */
.audio-visualizer {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 380rpx;
  opacity: 0.8;
  transform: scale(1.25);
}

/* 调整歌词区域样式 */
::v-deep .bing-lyric {
  padding-bottom: 80rpx; 
}

/* 进度条和设置栏容器 */
.progress-set-container {
  margin-top: 20rpx;
  position: relative;
  height: 60rpx;
}

/* 进度条容器 */
.progress-container {
  display: flex;
  align-items: center;
  width: 100%;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  transition: opacity 0.3s ease-in-out;
  .time-slider {
	  width: 100%;
  }
  .time-display {
	  margin: 0 2rpx;
  }
}

/* 设置栏容器 */
.volce-box {
  width: 100%;
  display: flex;
  align-items: center;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 2;
  transition: opacity 0.3s ease-in-out;
  
  .text-hint {
    box-sizing: border-box;
    width: 200rpx;
    color: #fff;
    margin-right: 5rpx;
    background: #3cc88c;
    font-weight: 800;
    padding: 15rpx;
    text-align: center;
    font-size: 30rpx;
  }
  
  .slider {
    display: flex;
    width: 100%;
    border: 1rpx solid #3cc88b7c;
    height: 62rpx;
    align-items: center;
    
    .text {
      padding: 0 10rpx;
      color: #3cc88c;
    }
    
    .slider-com {
      width: 100%;
    }
  }
  
  .slider.uv {
    width: 100%;
  }
}

/* 控制按钮 */
.play-btn-box {
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 10rpx 0;
  margin-top: 30rpx;
  
  .play-btn, .up-btn, .down-btn, .set-btn, .volce-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    height: 65px;
    width: 130rpx;
    background-color: #3cc88c;
    font-size: 28rpx;
    font-weight: 500;
    color: #FFFFFF;
    box-shadow: 0 6rpx 16rpx rgba(60, 200, 140, 0.4);
    transition: all 0.3s ease;
    border-radius: 50%;
  }
  
  .play-btn {
    animation: pulse 2s infinite;
    
    .img {
      height: 50%;
      width: 80%;
    }
  }
  
  .up-btn, .down-btn, .set-btn, .volce-btn {
    height: 45px;
    width: 90rpx;
    
    .img {
      height: 50%;
      width: 40%;
    }
  }
  
  .play-btn:active, .up-btn:active, .down-btn:active, .set-btn:active, .volce-btn:active {
    transform: translateY(-5rpx);
    box-shadow: 0 3rpx 8rpx rgba(60, 200, 140, 0.3);
  }
  
  @keyframes pulse {
    0% {
      box-shadow: 0 0 0 0 rgba(60, 200, 140, 0.7);
    }
    70% {
      box-shadow: 0 0 0 20rpx rgba(60, 200, 140, 0);
    }
    100% {
      box-shadow: 0 0 0 0 rgba(60, 200, 140, 0);
    }
  }
}

/* 调试信息 */
.debug-info {
  padding: 10rpx 20rpx;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  font-size: 24rpx;
  border-radius: 10rpx;
  margin: 10rpx;
  max-height: 200rpx;
  overflow: auto;
}

/* 覆盖式淡入淡出动画 */
.fade-cover-enter-from {
  opacity: 0;
  z-index: 2;
}

.fade-cover-leave-to {
  opacity: 0;
  z-index: 1;
}

.fade-cover-enter-active,
.fade-cover-leave-active {
  transition: opacity 0.3s ease-in-out;
}

.fade-cover-enter-to,
.fade-cover-leave-from {
  opacity: 1;
}

.social-icons {
    position: fixed;
    top: 50%;
    right: 20rpx;
    transform: translateY(-50%);
    display: flex;
    flex-direction: column;
    gap: 20rpx;
    background-color: #fff;
    padding: 20rpx;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.social-icon {
    width: 70rpx;
    height: 70rpx;
    border-radius: 50%;
    background-color: rgba(255, 255, 255, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.2s ease;

    &:active {
      transform: scale(0.95);
      background-color: rgba(255, 255, 255, 1);
    }
}
</style>